package com.cb.web.wasf.tag;

import com.cb.web.wasf.Principal;
import java.util.StringTokenizer;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.TryCatchFinally;

/**
 * @author CBO
 */
public class HasRoleTag extends BodyTagSupport implements TryCatchFinally {

    private static String ROLE_DELIMITER = ",";
    private String role;

    public void setRole(String role) {
        this.role = role;
    }

    @Override
    public int doStartTag() throws JspException {
        if (hasOneRole()) {
            return (EVAL_BODY_INCLUDE);
        } else {
            return (SKIP_BODY);
        }
    }

    @Override
    public int doEndTag() throws JspException {
        return (EVAL_PAGE);
    }

    private boolean hasOneRole() throws JspException {
        Principal principal = Principal.getFromPageContext(pageContext);
        if (principal != null) {
            StringTokenizer st = new StringTokenizer(role, ROLE_DELIMITER, false);
            if (principal.hasRole(st.nextToken().trim())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void doCatch(Throwable t) throws Throwable {
        throw t;
    }

    @Override
    public void doFinally() {
        this.role = null;
    }
}
